﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Resources;

namespace Tradukisto.Engine.ResourceProviders
{
    public class LocalizationResourceFileProvider : LocalizationProviderBase
    {
        private static readonly Dictionary<string, PropertyInfo> resourceTypesCache = new Dictionary<string, PropertyInfo>(0);

        object locker = new object();

        protected override string OnGetString(string cultureName, string key)
        {
            if (ResourceType == null)
                return null;

            PropertyInfo property = null;
            if (resourceTypesCache.ContainsKey(ResourceType.Name + key))
            {
                property = resourceTypesCache.Where(p => p.Key == ResourceType.Name + key).Select(p => p.Value).SingleOrDefault();
            }
            else
            {
                property = ResourceType.GetProperties()
                    .FirstOrDefault(p => p.PropertyType == typeof(ResourceManager));
                lock (locker)
                {
                    if (resourceTypesCache.ContainsKey(ResourceType.Name + key))
                    {
                        resourceTypesCache.Add(ResourceType.Name + key, property);
                    }
                }
            }
            if (property != null)
                return ((ResourceManager)property.GetValue(null, null)).GetString(key);

            return null;
        }

        public override Dictionary<string, string> GetAllStringsByControllerAndAction(string culture, string controller, string action)
        {
            throw new NotImplementedException();
        }

        public override Dictionary<string, string> GetAllStringsByControllerAndAction(string controller, string action)
        {
            throw new NotImplementedException();
        }

       
    }
}
